<template>
  <div class="book-info-container">
    <!-- 导航栏 -->
    <div class="navbar">
      <div class="navbar-left">
        <el-icon @click="handleBack" class="back-icon"><ArrowLeft /></el-icon>
        <span class="title">预订信息</span>
      </div>
    </div>
    
    <div class="book-info-content">
    <!-- 预订日期选择 -->
    <div class="date-section">
      <h4 class="section-subtitle">选择入住和退房时间</h4>
      <div class="date-picker">
        <el-date-picker
          v-model="checkInDate"
          type="date"
          placeholder="入住日期"
          :disabled-date="disabledCheckInDate"
          style="width: 100%; margin-bottom: 10px"
        />
        <el-date-picker
          v-model="checkOutDate"
          type="date"
          placeholder="退房日期"
          :disabled-date="disabledCheckOutDate"
          style="width: 100%"
        />
      </div>
      <div class="date-info" v-if="checkInDate && checkOutDate">
        <span>共 {{ calculateNights() }} 晚</span>
      </div>
    </div>

    <!-- 租客信息 -->
    <div class="tenant-section">
      <h4 class="section-subtitle">租客信息</h4>
      <el-form ref="tenantForm" :model="tenantInfo" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="tenantInfo.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="tenantInfo.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="tenantInfo.idCard" placeholder="请输入身份证号" />
        </el-form-item>
      </el-form>
    </div>

    <!-- 价格明细 -->
    <div class="price-detail-section">
      <h4 class="section-subtitle">价格明细</h4>
      <div class="price-detail">
        <div class="price-row">
          <span>房费 ({{ calculateNights() }}晚)</span>
          <span class="price-value">{{ calculateRoomPrice() }}</span>
        </div>
        <div class="price-row">
          <span>服务费</span>
          <span class="price-value">{{ serviceFee }}</span>
        </div>
        <div class="price-row">
          <span>押金</span>
          <span class="price-value">{{ deposit }}</span>
        </div>
        <div class="price-row total">
          <span>总计</span>
          <span class="price-value total-price">{{ calculateTotalPrice() }}</span>
        </div>
      </div>
    </div>

    <!-- 预订须知 -->
    <div class="notice-section">
      <h4 class="section-subtitle">预订须知</h4>
      <ul class="notice-list">
        <li>请确保填写的租客信息真实有效</li>
        <li>入住时需出示身份证原件</li>
        <li>如需取消预订，请提前24小时</li>
        <li>禁止在房间内吸烟和聚会</li>
        <li>请爱护房间设施，如有损坏需照价赔偿</li>
      </ul>
    </div>

    <!-- 提交按钮 -->
    <el-button type="primary" class="submit-btn" @click="handleSubmit">确认预订</el-button>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'

export default {
  name: 'BookInfo',
  components: {
    ArrowLeft
  },
  setup() {
    const router = useRouter()
    const route = useRoute()
    
    // 房源ID：优先从路由参数获取
    const roomId = computed(() => String(route.params.roomId || '1'))

    // 响应式数据
    const checkInDate = ref('')
    const checkOutDate = ref('')
    const tenantForm = ref(null)
    
    // 租客信息
    const tenantInfo = reactive({
      name: '',
      phone: '',
      idCard: ''
    })
    
    // 价格相关（模拟数据，实际应从API获取）
    const dailyPrice = ref(200)
    const serviceFee = computed(() => {
      return calculateNights() > 0 ? '¥' + Math.floor(dailyPrice.value * calculateNights() * 0.1) : '¥0'
    })
    const deposit = ref('¥1000')
    const PHONE_REG = /^1[3-9]\d{9}$/
    
    // 禁用入住日期
    const disabledCheckInDate = (time) => {
      return time.getTime() < Date.now() - 8.64e7 // 禁用今天之前的日期
    }
    
    // 禁用退房日期
    const disabledCheckOutDate = (time) => {
      if (!checkInDate.value) {
        return time.getTime() < Date.now() // 未选择入住日期时，禁用今天之前的日期
      }
      return time.getTime() <= new Date(checkInDate.value).getTime() // 禁用入住日期及之前的日期
    }
    
    // 计算入住天数
    const calculateNights = () => {
      if (!checkInDate.value || !checkOutDate.value) {
        return 0
      }
      const start = new Date(checkInDate.value)
      const end = new Date(checkOutDate.value)
      const diffTime = Math.abs(end - start)
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
      return diffDays
    }
    
    // 计算房费
    const calculateRoomPrice = () => {
      const nights = calculateNights()
      return '¥' + (dailyPrice.value * nights)
    }
    
    // 计算总价
    const calculateTotalPrice = () => {
      const nights = calculateNights()
      if (nights === 0) return '¥0'
      
      const roomPrice = dailyPrice.value * nights
      const serviceFeeNum = Math.floor(roomPrice * 0.1)
      const depositNum = 1000 // 模拟押金
      
      return '¥' + (roomPrice + serviceFeeNum + depositNum)
    }
    
    // 提交预订
    const handleSubmit = () => {
      // 表单验证
      if (!checkInDate.value) {
        ElMessage.warning('请选择入住日期')
        return
      }
      if (!checkOutDate.value) {
        ElMessage.warning('请选择退房日期')
        return
      }
      
      if (!tenantInfo.name) {
        ElMessage.warning('请输入租客姓名')
        return
      }
      if (!tenantInfo.phone) {
        ElMessage.warning('请输入手机号')
        return
      }
      if (!PHONE_REG.test(tenantInfo.phone)) {
        ElMessage.warning('请输入合法的手机号')
        return
      }
      if (!tenantInfo.idCard) {
        ElMessage.warning('请输入身份证号')
        return
      }
      
      // 构建预订数据
      const bookingData = {
        roomId: roomId.value,
        checkInDate: checkInDate.value,
        checkOutDate: checkOutDate.value,
        nights: calculateNights(),
        tenantInfo: {
          name: tenantInfo.name,
          phone: tenantInfo.phone,
          idCard: tenantInfo.idCard
        },
        priceDetail: {
          dailyPrice: dailyPrice.value,
          roomPrice: dailyPrice.value * calculateNights(),
          serviceFee: Math.floor(dailyPrice.value * calculateNights() * 0.1),
          deposit: 1000,
          totalPrice: dailyPrice.value * calculateNights() + Math.floor(dailyPrice.value * calculateNights() * 0.1) + 1000
        },
        bookingTime: new Date().toISOString()
      }
      
      console.log('提交预订数据:', bookingData)
      
      // 这里应该发送API请求
      // 模拟API请求
      setTimeout(() => {
        ElMessage.success('预订成功！')
        // 重置表单
        checkInDate.value = ''
        checkOutDate.value = ''
        tenantInfo.name = ''
        tenantInfo.phone = ''
        tenantInfo.idCard = ''
        
        // 预订成功后返回到租房详情页
        router.push({ name: 'RentRoomDetail', params: { id: roomId.value } })
      }, 1000)
    }
    
    // 返回上一页
    const handleBack = () => {
      router.back()
    }
    
    return {
      roomId,
      checkInDate,
      checkOutDate,
      tenantForm,
      tenantInfo,
      serviceFee,
      deposit,
      disabledCheckInDate,
      disabledCheckOutDate,
      calculateNights,
      calculateRoomPrice,
      calculateTotalPrice,
      handleSubmit,
      handleBack
    }
  }
}
</script>

<style scoped>
.book-info-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

/* 导航栏样式 */
.navbar {
  background-color: #fff;
  padding: 12px 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.navbar-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.back-icon {
  font-size: 20px;
  cursor: pointer;
}

.title {
  font-size: 18px;
  font-weight: 700;
}

.book-info-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.section-subtitle {
  font-size: 16px;
  font-weight: 700;
  margin: 20px 0 12px;
}

/* 日期选择样式 */
.date-picker {
  margin-bottom: 8px;
}

.date-info {
  text-align: right;
  color: #666;
  font-size: 14px;
}

/* 租客信息样式 */
.tenant-section {
  margin-top: 20px;
}

/* 价格明细样式 */
.price-detail {
  background-color: #f9f9f9;
  padding: 12px;
  border-radius: 8px;
}

.price-row {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  font-size: 14px;
}

.price-row.total {
  margin-top: 8px;
  padding-top: 12px;
  border-top: 1px solid #e0e0e0;
  font-weight: 700;
}

.price-value {
  color: #666;
}

.price-value.total-price {
  color: #ff4757;
  font-size: 18px;
}

/* 预订须知样式 */
.notice-list {
  color: #666;
  font-size: 14px;
  line-height: 1.8;
}

.notice-list li {
  margin-bottom: 4px;
}

/* 提交按钮样式 */
.submit-btn {
  width: 100%;
  margin-top: 24px;
  height: 44px;
  font-size: 16px;
}
</style>